package com.zgf.jdbcTemplate;

import com.zgf.domain.Account;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.lang.Nullable;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * JdbcTemplate CRUD操作
 *
 * */
public class JdbcTemplateDemo3 {



   //查询所有
   public static void main(String[] args) {
       ApplicationContext ac =new ClassPathXmlApplicationContext("applicationContext.xml");
       JdbcTemplate jt = ac.getBean("jdbcTemplate",JdbcTemplate.class);
    //   List<Account> accouts=jt.query("select * from Account ",new AccountRowMapper());
     /*  List<Account> accouts=jt.query("select * from Account ",new BeanPropertyRowMapper<Account>(Account.class));
       for (Account accout : accouts) {
           System.out.println(accout);
       }
       */


       //查询一个
       List<Account> accout=jt.query("select * from Account WHERE  id =?",new BeanPropertyRowMapper<Account>(Account.class),10);

       System.out.println(accout.isEmpty()?"数据库不存在":accout.get(0));

       //返回一行或者一列（使用聚合函数，但不使用group by 语句）
       Integer a = jt.queryForObject("SELECT count(*) from account where money> ?", Integer.class, 1000f);
       System.out.println(a);
   }





  static class AccountRowMapper implements RowMapper<Account>{


       @Override
       public Account mapRow(ResultSet rs, int i) throws SQLException {
           Account account =new Account();
           account.setId(rs.getInt("id"));
           account.setName(rs.getString("name"));
           account.setMoney(rs.getFloat("money"));
           return account;
       }
   }

}
